﻿using System;
using LitJson;
using UnityEngine;
using UnityEngine.Networking;
using xuni;

namespace xres
{


    public class GetTextAction : BaseAsyncAction
    {
        /// <summary>
        /// 服务器错误
        /// </summary>
        public const string Err_Http = "Err_Http";
        /// <summary>
        /// 网络错误
        /// </summary>
        public const string Err_Network = "Err_Network";

        bool _addTimeStamp;
        string _getUrl = "";
        int _leftRetryCount = 0;
        AsyncOperation _op;

        public string Text { get; internal set; }


        public float CheckProgress()
        {
            switch (_state)
            {
            case BaseAsyncActionState.Init:
                return 0;

            case "Loading":
                return _op.progress;

            }

            return 1;
        }


        public void GetText(string url, bool addTimeStamp)
        {
            switch (_state)
            {
            case BaseAsyncActionState.Init:
            case BaseAsyncActionState.Finish:
                //可用于重复执行任务
                break;

            default:
                return;
            }

            _state = "Loading";
            _leftRetryCount = 3;
            _getUrl = url;
            _addTimeStamp = addTimeStamp;

            if (false) Debug.Log($"GetText: url: {url}");
            SendRequest();
        }

        void SendRequest()
        {
            --_leftRetryCount;

            var url = "";
            if (_addTimeStamp)
                url = HttpUtils.AddTimeStamp(_getUrl);
            else
                url = _getUrl;

            var webReq = UnityWebRequest.Get(url);
            webReq.timeout = 2;
            var request = webReq.SendWebRequest();
            _op = request;
            request.completed += OnComplete_HttpGet;
        }

        void OnComplete_HttpGet(AsyncOperation op)
        {
            if (false) Debug.Log($"GetText: complete");
            _op = null;

            var request = (UnityWebRequestAsyncOperation)op;
            var webReq = request.webRequest;
            using (webReq)
            {
                if (!webReq.isDone || webReq.isNetworkError) //超时或者网络不通
                {
                    if (_leftRetryCount <= 0)
                    {
                        SetError(Err_Network, $"GetText: timeout and leftRetryCount <= 0, end");
                        Debug.Log(ErrMsg);
                        SetFinishAndNotify(ErrMsg);
                    }
                    else
                    {
                        Debug.Log($"GetText: timeout, retry: {_leftRetryCount}");
                        SendRequest();
                    }
                }
                else if (webReq.isHttpError || !string.IsNullOrEmpty(webReq.error)) //http错误, 重试没用
                {
                    SetError(Err_Http, $"GetText: http error, {webReq.error}");
                    Debug.Log(ErrMsg);
                    SetFinishAndNotify(ErrMsg);
                }
                else
                {
                    this.Text = webReq.downloadHandler.text;
                    if (false) Debug.Log($"GetText: text: {this.Text}");

                    SetError("", "");
                    SetFinishAndNotify("");
                }
            }
        }

    } //end of class


}
